// 
import {Model} from './abnormalModel'
import { formatDate, objectDateToTimestamp } from 'pub-bbx-utils';
import _ from "lodash";
import {COLORS} from '../report/common/colorLModel'
/** api */
import * as TaskApi from '@src/api/TaskApi.ts';
/**
 * components
 */
import HeaderSelect from './components/headerSelect.vue'
import NoDataView from '@src/component/common/NoDataView';

/* echarts */
import echarts from 'echarts';

import { isOpenData, openAccurateTab } from '@src/util/platform';
import { checkButtonDisplayed } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { showExportListAlert } from '@src/util/alert';
import { t } from '@src/locales';
import { defaultTableData } from '@src/util/table'
// table列表
const PIETABLELIST = [{
  displayName: t('common.form.preview.taskNo.label'),
  fieldName: 'taskNo',
},
{
  displayName: t('common.fields.customer.displayName'),
  fieldName: 'customerName',
},
{
  displayName: t('common.fields.taskType.displayName'),
  fieldName: 'templateName',
},
{
  displayName: t('common.fields.executorUser.displayName'),
  fieldName: 'excutorName',
},
{
  displayName: t('common.fields.createUser.displayName'),
  fieldName: 'createName',
},
{
  displayName: t('common.fields.createTime.displayName'),
  fieldName: 'createTime',
},
{
  displayName: t('common.task.exceptionNode'),
  fieldName: 'action',
},
{
  displayName: t('report.abnormalList.anomaliesCause'),
  fieldName: 'exceptionNameList',
},
{
  displayName: t('report.abnormalList.anomaliesTotal'),
  fieldName: 'total',
},
];
const statusObj = {
  refused:t('common.task.exceptionStatus.refused'),
  paused:t('common.task.exceptionStatus.pause'),
  reallot:t('common.task.exceptionStatus.allot'),
  rollback:t('common.task.exceptionStatus.rollback'),
  offed:t('common.task.exceptionStatus.offed'),
}
export default {
  name: 'abnormal',
  data() {
    return {
      defaultTableData,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      type: '',
      chartType: '',
      pieTabList: [], // 饼行table列表
      columnarTabList: [], // 柱状图table列表
      tableNames: PIETABLELIST,
      checkTab: '', // 柱状图原因选中
      PieTime: '', // 图表时间
      pieAction: '', // 饼图节点
      barAction: '',
      exceptionName: '', // 柱状图原因
      PieChartList: [],
      ColumnarList: [],
      Pietotal: 0,
      curtotal: 0,
      curPageParams: {page: 1, pageSize: 10},
      PiePageParams: {page: 1, pageSize: 10},
      taskCustomExceptionNodeList: [{exceptionName: t('common.base.all'), englishName: ''}],
      params: {tagIds: [], executorUserIds: [], createTimeStart: '', createTimeEnd: '', taskExceptionType: 1},
      columnarParams: {tagIds: [], executorUserIds: [], createTimeStart: '', createTimeEnd: '', action: ''},
      checkExceptionTab: 1,
      taskExceptionNodeList: [
        {
          exceptionName: t('report.abnormalList.currentAbnormalWorkOrder'),
          englishName: 1,
          // 导出埋点用，有新增记得带上这个，顺便更新下埋点文档~
          trackLabel: 'CURRENT_ABNORMAL_TASK'
        },
        {
          exceptionName: t('report.abnormalList.onceAbnormalWorkOrder'),
          englishName: 2,
          trackLabel: 'ONCE_ABNORMAL_TASK'
        }
      ]
    }
  },
  components: {
    [HeaderSelect.name]: HeaderSelect,
    [NoDataView.name]: NoDataView
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data') || '{}')
      return initData.auths?.REPORT_EXPORT || 0
    },
  },
  mounted() {
    this.type = this.$route.query.type || 'pie-chart'
    // 原本的type不明确，所以做个转化，为了用于埋点~
    const chartTypeObj = {
      'pie-chart': 'task-exception-node',
      'histogram': 'task-abnormal-reason',
    }
    this.chartType = chartTypeObj[this.type]
    this.getTurnOnTaskExceptionNodeInfo()
  },

  methods: {
    /** 获取用户开启的配置节点 以及工单搜索范围 和 异常原因字段值 */
    async getTurnOnTaskExceptionNodeInfo() {
      const {success, result} = await TaskApi.getTurnOnTaskExceptionNodeInfo()
      const statusKeys = Object.keys(statusObj)
      if(success) {
        let taskCustomExceptionNodeList = result.taskCustomExceptionNodeList.filter(item => {
          return item.switch && item
        }).forEach(item => {
          const { englishName } = item
          if (statusKeys.includes(englishName)) {
            this.taskCustomExceptionNodeList.push({...item,exceptionName:statusObj[englishName]})
          }
        })
      }

    },
    // 饼图数据
    async chart() {
      const {params} = this
      const {succ, data} = await TaskApi.chart(params)
      if (succ) {
        this.pieTabList = []
        let taskExceptionVOList = data.taskExceptionVOList.map(item => {
          Model.forEach(v => {
            if (item.action === v.action) {
              item.actionName = v.actionNmae
            }
          })
          return item
        })
        this.PieChartList = taskExceptionVOList
        this.$nextTick(() => {
          this.PieChart(taskExceptionVOList)
        })
      }

    },
    // 柱状图数据
    async histogram() {
      const {columnarParams} = this
      const {succ, data} = await TaskApi.histogram(columnarParams)
      if (succ) {
        this.columnarTabList = []

        this.ColumnarList = data.taskExceptionVOList
        this.$nextTick(() => {
          this.Columnar(data.taskExceptionVOList)
        })
      }
    },
    // 负责人
    excutorName(v) {
      if(v.name) {
        this.columnarParams.executorUserIds = v.event
        this.histogram()
      } else {
        this.params.executorUserIds = v.event
        this.chart()
      }
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_MANAGER_SEARCH', this.$track)
    },
    // 团队
    update(v) {
      if(v.name) {
        this.columnarParams.tagIds = v.ids ? v.ids.split(',') : []
        this.histogram()
      } else {
        this.params.tagIds = v.ids ? v.ids.split(',') : []
        this.chart()
      }

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    // 时间
    ceratTime(v) {
      const [start, end] = v.event || []
      this.params.createTimeStart = start
      this.params.createTimeEnd = end

      if(v.name) {
        this.columnarParams.createTimeStart = start
        this.columnarParams.createTimeEnd = end
        this.histogram()
      }else {
        this.chart()
      }

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    },
    /* 分页条数切换 */
    handleSizeChange(value) {
      this.PiePageParams.page = 1
      this.PiePageParams.pageSize = value;
      this.pieConsole()
    },
    /* 分页页数切换 */
    handlePageChange(value) {
      this.PiePageParams.page = value;
      this.pieConsole()
    },

    /* 分页条数切换 */
    CurhandleSizeChange(value) {
      this.curPageParams.page = 1
      this.curPageParams.pageSize = value;
      this.columnarConsole()
    },
    /* 分页页数切换 */
    CurhandlePageChange(value) {
      this.curPageParams.page = value;
      this.columnarConsole()
    },

    /* 饼图 */
    PieChart(taskExceptionVOList) {
      let names = taskExceptionVOList.map(item => {return item.actionName})
      let data = taskExceptionVOList.map(item => {return {value: item.actionNum, name: item.actionName, action: item.action}})

      const pieChart = echarts.init(this.$refs.piechart)
      window.addEventListener('resize', _.debounce(function(){
        pieChart.resize();
      }))
      let option = {
        color: COLORS,
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: names
        },
        series: [{
          type: 'pie',
          radius: '70%',
          center: ['50%', '50%'],
          data,
          label: {
            normal: {
              formatter: '{b} : {c} ({d}%)'
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      pieChart.setOption(option)
      // 添加点击事件
      pieChart.on('click', this.pieConsole)
    },

    // 饼图table
    async pieConsole(event = '') {
      if (event) {
        const {action} = event.data
        this.pieAction = action
        this.PiePageParams = {page: 1, pageSize: 10}
      }

      const {succ, data} = await TaskApi.chartList({...this.params, ...this.PiePageParams, ...{action: this.pieAction}})
      if (succ) {
        this.Pietotal = data.total

        this.pieTabList = data.list.map(item => {
          item.timeName = formatDate(item.createTime)
          return item
        })
      }
    },
    /* 柱状图 */
    Columnar(taskExceptionVOList) {
      if (!this.$refs.columnar) return
      
      const nams = !this.checkTab ? taskExceptionVOList.map(item => {
        this.taskCustomExceptionNodeList.forEach(v => {
          if(v.englishName === item.action) {
            item.exceptionName = `${item.exceptionName}-${v.exceptionName}`
          }
        })
        return item.exceptionName
      }) : taskExceptionVOList.map(item => { return item.exceptionName})
      const data = taskExceptionVOList.map(item => {return {value: item.exceptionNameNum, action: item.action, exceptionName: item.exceptionName}})
      const columnarChart = echarts.init(this.$refs.columnar)
      window.addEventListener('resize', _.debounce(function(){
        columnarChart.resize();
      }))
      let option = {
        color: ['#269fd6'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          }
        },
        grid: {
          top: '1%',
          left: '3%',
          width: '96%'
        },
        xAxis: [{
          type: 'category',
          data: nams,
        }],
        yAxis: [{
          type: 'value',
        }],
        dataZoom: [{
          show: true,
          start: 0,
          end: 100
        }],
        series: [{
          type: 'bar',
          data,
          barWidth: 40
        }]
      };

      columnarChart.setOption(option)

      // 添加点击事件
      columnarChart.on('click', this.columnarConsole)
    },

    // 柱状图table
    async columnarConsole(event = '') {
      if (event) {
        const {action, exceptionName} = event.data
        this.barAction = action
        this.columnarParams.action = action
        this.exceptionName = exceptionName.split('-')[0]
        this.curPageParams = {page: 1, pageSize: 10}
      }
      const {succ, data} = await TaskApi.histogramList({...this.columnarParams, ...this.curPageParams, ...{exceptionName: this.exceptionName}})
      if (succ) {
        this.curtotal = data.total

        this.columnarTabList = data.list.map(item => {
          item.timeName = formatDate(item.createTime)
          return item
        })
      }
    },
    // 饼图判断多少条数据
    async chartTotal(type) {
      const {params} = this
      params.action = type !== 'all' ? this.pieAction : ''
      const {succ, data} = await TaskApi.chartTotal(params)
      if (succ) {
        if (data.total > 5000) {
          this.$platform.alert(this.$t('common.base.tip.exportMostTip'))
          return
        }
        this.actionExport(type)
      }
      
      const tab = this.taskExceptionNodeList.find(v => this.checkExceptionTab === v.englishName)?.trackLabel
      this.exportTrack(type === 'all', tab)
    },

    // 饼图判断多少条数据
    async histogramTotal(type) {
      const {columnarParams} = this
      columnarParams.action = type !== 'all' ? this.barAction : ''
      const {succ, data} = await TaskApi.histogramTotal(columnarParams)
      if (succ) {
        if (data.total > 5000) {
          this.$platform.alert(this.$t('common.base.tip.exportMostTip'))
          return
        }
        this.reasonExport(type)
      }

      const tab = !this.checkTab ? 'ALL' : this.checkTab.replace(/([A-Z])/g, '_$1').toLocaleUpperCase()
      this.exportTrack(type === 'all', tab)
    },

    exportTrack(isExportAll, tab) {
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType,
        tab
      }, '*')
    },
    // 饼图导出
    async actionExport(type) {
      let action = this.pieAction;
      if (type == 'all') {
        action = ''
      }
      const {executorUserIds, createTimeStart, tagIds, createTimeEnd} = this.params
      const params = {
        userIds: executorUserIds,
        tagIds,
        createTimeStart,
        createTimeEnd,
        action,
      }
      const {succ, message} = await TaskApi.actionExport(params)
      // this.$platform.alert(message)
      // if (succ) {
      //   window.parent.showExportList();
      //   window.parent.exportPopoverToggle(true);
      // }
      if (succ) {
        showExportListAlert(message)
      }else{
        this.$platform.alert(message)
      }

    },
    // 柱状图导出
    async reasonExport(type) {
      let exceptionName = ''
      const {executorUserIds, createTimeStart, tagIds, createTimeEnd, action} = this.columnarParams
      const params = {
        userIds: executorUserIds,
        tagIds,
        createTimeStart,
        createTimeEnd,
        action: type === 'all' ? '' : action,
        exceptionName
      }
      const {succ, message} = await TaskApi.reasonExport(params)
      // this.$platform.alert(message)
      // if (succ) {
      //   window.parent.showExportList();
      //   window.parent.exportPopoverToggle(true);
      // }
      if (succ) {
        showExportListAlert(message)
      }else{
        this.$platform.alert(message)
      }
    },
    /* tab切换 */
    TabSwitch(v) {
      this.checkTab = v
      this.columnarParams.action = v
      this.histogram()
    },
    /* tab切换 */
    TabExceptionSwitch(v) {
      this.checkExceptionTab = v
      this.params.taskExceptionType = this.checkExceptionTab
      this.chart()
    },

    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    /** */
    abText(action) {
      let texts = []
      Model.forEach(v => {
        action.forEach(item => {
          if (item === v.action) {
            texts.push(v.actionNmae)
          }
        })
      })
      return texts.join('、')
    }
  }
};